package it.unipd.dei.bd.icineasti.servlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import it.unipd.dei.bd.icineasti.database.GetLocandinaEventoDatabase;
import it.unipd.dei.bd.icineasti.resource.Immagine;

/**
 * Caricamento di un'immagine dal db, come parametro d'ingresso il codice dell'evento
 * 
 * @author Morris Antonello
 */
public class ImageServlet extends AbstractDatabaseServlet {

    private static final int DEFAULT_BUFFER_SIZE = 10240;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException
    {
        // ID dal request.
        String imageId = request.getParameter("id");

        if (imageId == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Cerca l'immagine nel db dato l'imageID
        Connection con = null;
        Immagine image = null;
		try {
			con = DS.getConnection();
			image =  new GetLocandinaEventoDatabase(con, Integer.parseInt(imageId)).getLocandina();
		} catch (SQLException e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR); // 500.
            return;
		}
			
        // Controllo sull'immagine restituira dal db
        if (image == null) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND); // 404.
            return;
        }

        // Inizializzazione della servlet response
        response.reset();
        response.setBufferSize(DEFAULT_BUFFER_SIZE);
        response.setContentType(image.getContentType());
        response.setContentLength(image.getContent().length);
        response.setHeader("Content-Disposition", "inline; filename=\"" + image.getName() + "\"");

        BufferedOutputStream output = null;

        try {
            output = new BufferedOutputStream(response.getOutputStream(), DEFAULT_BUFFER_SIZE);
            output.write(image.getContent());
        } finally {
            close(output);
        }
    }

    private static void close(Closeable resource) {
        if (resource != null) {
            try {
                resource.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

}